package com.lv.handler;

import cn.hutool.json.JSONUtil;
import com.lv.common.AjaxResult;
import com.lv.common.untils.RedisCache;
import com.lv.common.untils.TokenUntil;
import com.lv.entity.LoginUser;
import com.lv.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 * <p>
 *
 * </p>
 *
 * @Author: 凉薄
 * @Date: 2022/01/09/15:19
 * @Description:
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    UserService userService;
    @Autowired
    RedisCache redisCache;
    @Autowired
    TokenUntil tokenUntil;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if(authentication!=null){
            new SecurityContextLogoutHandler().logout(request,response,authentication);
        }
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream=response.getOutputStream();
        Long id = tokenUntil.getIdByToken(request);
        redisCache.deleteObject("token:"+id);
        userService.clearAuthoritiesInfo(id);
        AjaxResult success = AjaxResult.success("注销成功！");
        outputStream.write(JSONUtil.toJsonStr(success).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
